#!/usr/bin/env python
# encoding: utf-8
import sys, os, requests, socket, re, time, json
from xml.dom import minidom


socket.setdefaulttimeout(10)    # 10s超时

GET_URL = 'http://m.lzgd.com.cn/inc/lzgd/BikeStation/NikeStationlist.aspx'
USER_AGENT = 'Apache-HttpClient/UNAVAILABLE (java 1.4)'


def get_attrvalue(node, attrname):
     return node.getAttribute(attrname) if node else ''

def get_nodevalue(node, index = 0):
    return node.childNodes[index].nodeValue if node else ''

def get_xmlnode(node, name):
    return node.getElementsByTagName(name) if node else []

def GetResult(html):
    # 解析XML
    dom = minidom.parseString(html)
    root = dom.documentElement
    #
    result = []
    rows = get_xmlnode(root, 'Table')
    for row in rows: 
        ridNode = get_xmlnode(row, 'ID')                    # 记录ID
        shortTitleNode = get_xmlnode(row, 'Short_Title')    # 站点名称
        stationIDNode = get_xmlnode(row, 'StationID')       # 站点ID
        areaNameNode = get_xmlnode(row, 'Areaname')         # 区域名称
        restoreCountNode = get_xmlnode(row, 'RestoreCount') # 可还
        rentCountNode = get_xmlnode(row, 'RentCount')       # 可租
        dateStringNode = get_xmlnode(row, 'DateString')     # 时间?
        gpsXNode = get_xmlnode(row, 'Gpsx')                 # X坐标
        gpsYNode = get_xmlnode(row, 'Gpsy')                 # Y坐标
        shortMSYNode = get_xmlnode(row, 'Short_MS')         # 不知道

        rid = int(get_nodevalue(ridNode[0]))
        shortTitle = get_nodevalue(shortTitleNode[0])
        stationID = int(get_nodevalue(stationIDNode[0]))
        areaName = get_nodevalue(areaNameNode[0])
        restoreCount = int(get_nodevalue(restoreCountNode[0]))
        rentCount = int(get_nodevalue(rentCountNode[0]))
        dateString = get_nodevalue(dateStringNode[0])
        gpsX = get_nodevalue(gpsXNode[0])
        gpsY = get_nodevalue(gpsYNode[0])
        shortMSY = get_nodevalue(shortMSYNode[0])
        
        result.append({'rid':rid, 'shortTitle':shortTitle, 'stationID':stationID, 'areaName':areaName, 'restoreCount':restoreCount,
                       'rentCount':rentCount, 'dateString':dateString, 'gpsX':gpsX, 'gpsY':gpsY, 'shortMSY':shortMSY
                      })
    return result
    
def GetData(tid, page):
    # 发送消息
    url = '{0}?tid={1}&page={2}'.format(GET_URL, tid, page)
    cookies = { }
    headers = {
               'User-Agent': USER_AGENT
              }
    r = requests.get(url, headers=headers)
    return r.text.strip()

def GetStation(area):
    # 获取区域里的所有站点
    result = []
    for page in range(1, 10):
        for r in range(1, 5):
            # 重试4次
            html = GetData(area, page)
            if (html.startswith('<NewDataSet>')==False):
                html = ''
                print area, page, time.strftime(r'%m/%d %H:%M:%S')
                continue
            else: break

        if (html == ''):
            print '本次获取失败.'
            break
        stations = GetResult(html.encode('utf-8'))
        if (len(stations)==0): break
        else: result.extend(stations)
    return result

if __name__=='__main__':
    # 程序入口
    stations = []
    stations.extend(GetStation(1))
    stations.extend(GetStation(2))
    stations.extend(GetStation(3))
    stations.extend(GetStation(4))

    rentCount = 0       # 可租
    restoreCount = 0    # 可还

    for station in stations:
        rentCount += station['rentCount']
        restoreCount += station['restoreCount']

    print u'当前时间: {0}'.format(time.strftime(r'%m/%d %H:%M:%S'))
    print u'站点数量: {0}'.format(len(stations))
    print u'可租总数: {0}'.format(rentCount)
    print u'可还总数: {0}'.format(restoreCount)
    
    #encodedjson = json.dumps(stations)
    #print encodedjson
    
